package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.1从请求头中获取token，并处理
        String token= request.getHeader("Authorization");
        token=token.replace("Bearer","").trim();
        log.info("token="+token);
        //1.2判断，token是否为空
        if (!StringUtils.isNotEmpty(token)) {
            //为空时，返回错误结果
            ResultInfo resultInfo=ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        //2.解析token,解析失败表明被篡改过
        try{
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            ResultInfo resultInfo=ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        //3.从redis根据token查询
        User user=(User) redisTemplate.opsForValue().get("TOKEN_" + token);
        if (user == null) {
            //没查到
            ResultInfo resultInfo=ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);
            response.getWriter().write(json);
            return false;
        }
        //4.以上都满足后就证明成功了，先续期，再放行
        redisTemplate.opsForValue().set("TOKEN_" + token,user,1, TimeUnit.DAYS);
        //将用户信息存储到ThreadLocal
        UserHolder.set(user);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除user
        UserHolder.remove();
    }
}
